<template>
  <div class="HOME" style="position: relative;height: 100%;position: fixed; bottom: 0;width: 100%;"> 
    <!--  -->
    <!-- {{ userId }} -->
    <template v-if="indexs == 0">
      <Home :params="Params" @seebnt="seebnt"  @gameIndex="gameIndex" :list="homeList" :user="user"></Home>
    </template>
    <template v-if="indexs == 1">
      <Game :params="Params" :share="share" :gameUrl="gameUrl" :countdown="countdown" :user="user"></Game>
    </template>
    <template v-if="indexs == 2">
      <share :share="share" @gameIndex="gameIndex" :user="user"></share>
    </template>
    <template v-if="indexs == 3">
      <leaderboard :params="Params" :list="leaderList" :user="user"></leaderboard>
    </template>
    <template v-if="indexs == 4">
      <Airdrop :params="Params" @gameIndex="gameIndex" :cumulateDays="cumulateDays"  :taskList="taskList" :compeletedList="compeletedList" :taskTime="taskTime" @checkHandel="checkHandel" :user="user"></Airdrop>
    </template>

    <!-- <button @click="expand">Expand Webview</button>
    <button @click="toggleMainButton">Hide Main Button</button> -->
    <tab-bar :AirdropIndex="indexs" @tanCilck="tanCilck"></tab-bar>
    
  </div>
</template>

<script>

const DemoApp = {
  initData: Telegram.WebApp.initData || '',
  initDataUnsafe: Telegram.WebApp.initDataUnsafe || {},
  MainButton: Telegram.WebApp.MainButton,
  init(options) {
    document.body.style.visibility = '';
    Telegram.WebApp.ready();
    // Telegram.WebApp.MainButton.setParams({
    //   text: 'CLOSE App',
    //   is_visible: true
    // }).onClick(DemoApp.close);
  },
  expand() {
    Telegram.WebApp.expand();
  },
  close() {
    Telegram.WebApp.close();
  },
  toggleMainButton(el) {
    const mainButton = Telegram.WebApp.MainButton;
    if (mainButton.isVisible) {
      mainButton.hide();
      el.innerHTML = 'Show Main Button';
    } else {
      mainButton.show();
      el.innerHTML = 'Hide Main Button';
    }
  },
  sendMessage(msg_id, with_webview) {
    if (!DemoApp.initDataUnsafe.query_id) {
      alert('WebViewQueryId not defined');
      return;
    }

    document.querySelectorAll('button').forEach((btn) => btn.disabled = true);

    const btn = document.querySelector('#btn_status');
    btn.textContent = 'Sending...';

    DemoApp.apiRequest('sendMessage', {
      msg_id: msg_id || '',
      with_webview: !DemoApp.initDataUnsafe.receiver && with_webview ? 1 : 0
    }, function (result) {
      document.querySelectorAll('button').forEach((btn) => btn.disabled = false);

      if (result.response) {
        if (result.response.ok) {
          btn.textContent = 'Message sent successfully!';
          btn.className = 'ok';
          btn.style.display = 'block';
        } else {
          btn.textContent = result.response.description;
          btn.className = 'err';
          btn.style.display = 'block';
          alert(result.response.description);
        }
      } else if (result.error) {
        btn.textContent = result.error;
        btn.className = 'err';
        btn.style.display = 'block';
        alert(result.error);
      } else {
        btn.textContent = 'Unknown error';
        btn.className = 'err';
        btn.style.display = 'block';
        alert('Unknown error');
      }
    });
  }
}
DemoApp.init();

import Api from '@/api/api';
import TabBar from '@/components/Tabar/index.vue'
import Airdrop from '@/components/Airdrop.vue';
import Leaderboard from '@/components/Leaderboard.vue';
import Share from '@/components/Share.vue';
import Game from '@/components/game.vue';
import Home from '@/components/home.vue';
export default {
  components: {
    TabBar,
    Airdrop,
    Leaderboard,
    Share,
    Game,
    Home
   },
  data() {
    return {
      userId: null,
      indexs: 0,
      user: {},
      gameUrl: '',
      leaderList: [],
      checkHandelIndex: 0,
      timer: null,
      taskTime: '',
      homeList: [], //首页任务展示
      taskList: [],//所有空投任务
      loggedIn: null,
      cumulateDays: [],
      checkHandel: 0,
      share: {},
      timerUser: null,
      compeletedList: [],
      totalSeconds: 3600,
      intervalId: null, // 存储interval的id
      Params:{}
    };
  },
  created() {
    
    this.userId = JSON.stringify(DemoApp.initDataUnsafe, null, 2)
    if (this.userId) {
 
      this.tgLogin()
       this.timerUser = setInterval(() => {
        this.getUserInfo()
         this.leaderboard()   
       }, 2000)

      setInterval(() => {
        this.gettask()
       },4000)
    }
    

   
  },
  
  beforeCreate() {
    clearInterval(this.timerUser)
  },

  beforeDestroy() {
    // 清除定时器
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  mounted() {
    document.body.style.overflow = 'hidden';
    document.body.style.position = 'fixed';
    document.body.style.width = '100%';

  },
  computed: {
    countdown() {
      // 计算剩余时间
      let hours = Math.floor(this.totalSeconds / 3600);
      let minutes = Math.floor((this.totalSeconds % 3600) / 60);
      let seconds = this.totalSeconds % 60;

      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      // seconds = seconds < 10 ? '0' + seconds : seconds;

      return `${hours}:${minutes}`;
    },
  },
  watch: {
    'user.hp'(o, c) {
      if (o < 8) {
        this.intervalId = setInterval(this.updateCountdown, 1000);
      }
      if (o == 8) {
        if (this.intervalId) {
          clearInterval(this.intervalId);
        }
      }
    }
  },
  methods: {
    updateCountdown() {
      if (this.totalSeconds > 0) {
        this.totalSeconds -= 1;
      }
    },
    init() {
      this.leaderboard()
      this.getUserInfo()
      this.gettask()
      this.getShare()
      this.getsignrecord()
      this.gettaskinfo()
      this.expand()
    },
    ddd() {
      DemoApp.share({
        content: ({
          title: 'Taozi',
          url: 'https://t.me/JumpAndSay_bot/Jump?start=' + this.user.chatId
        })
      })
    },
    gettaskinfo() {
      Api.get('taskinfo/completedPage').then(res => {
        if (res.code == 200) {
          this.compeletedList = res.data.records
        }
      })
    },
    getsignrecord() {
      Api.get('signrecord/user').then(res => {
        if (res.code == 200) {
          if (res.data.cumulateDays <= 0) {
            this.cumulateDays.push(res.data.cumulateDays)
            return
          }
          for (var i = 0; i < res.data.cumulateDays; i++) {
            this.cumulateDays.push(i + 1)
          }
        }
      })
    },
    getShare() {
      Api.post('userinfo/getShareInfo').then(res => {
        if (res.code) {
          this.share = res.data
        }
      })
    },
    seebnt(i) {
      this.indexs = i
    },
   
    gettask() {
      let one = []
      let two = []
      let three = []
      let list = []
      Api.get('taskinfo/page').then(res => {
        if (res.code == 200) {
          res.data.records.forEach((item, index) => {
            if (index <= 2) this.homeList.push(item)
            if (item.type < 4) one.push(item)
            if (item.type == 4) two.push(item)
            if (item.type > 4) three.push(item)
          })
          list = [{title:'Get started',list:one},{title:'Daily Tasks',list:two},{title:'Social Tasks',list:three}]
          this.taskList = list
        }
      })
    },
     countDown(time) {
      var nowTime = +new Date()
      var inputTime = +new Date(time * 1000);
      if (nowTime === inputTime) return clearInterval(this.timer)
      var times = (inputTime - nowTime) / 1000;
      var d = parseInt(times / 60 / 60 / 24);
      d = d < 10 ? '0' + d : d;
      var h = parseInt(times / 60 / 60 % 24);
      h = h < 10 ? '0' + h : h;
      var m = parseInt(times / 60 % 60);
      m = m < 10 ? '0' + m : m;
      var s = parseInt(times % 60);
      s = s < 10 ? '0' + s : s;

      return d + 'd' + h + 'h' + m + 'm' + s + 's'
    },
    getUserInfo() {
      Api.get('/userinfo').then(res => {
        if (res.code == 200) {
          this.user = res.data
          localStorage.setItem('userInfo', JSON.stringify(res.data))

          this.timer = setInterval(() => {
            this.taskTime = this.countDown(res.data.taskTime)
          }, 1000)
          
        }
      })
    },
    checkHandel(i) {
      this.checkHandelIndex == i
    },
    leaderboard() {
      Api.get('leaderboard/list').then(res => {
        if (res.code == 200) {
          this.leaderList = res.data
        }
      })
    },
    gameIndex(i) {
      this.indexs = i
    },
    tanCilck(i) {
      this.indexs = i
    },
     // 禁用滚动
    disableScroll() {
      document.body.style.overflow = 'hidden';
      document.body.style.position = 'fixed';
      document.body.style.width = '100%';
    },
    // 授权登录
    tgLogin() {
      let user = JSON.parse(this.userId)
      localStorage.setItem('users',user)
      //   user.user?user.user.id : 7455856649
        // 
         Api.post('userinfo/telegram/login', { chatId: user.user ? user.user.id : 7455856649, userName: user.user.first_name  }).then(res => {
           this.loggedIn = res
           if (res.code == 200) {
             localStorage.setItem('userInfo', res.data)
             localStorage.setItem('token', res.data.thirdSession)
             this.user = res.data
             this.gameUrl = `https://gameab.zhongyigames.com/nzp/tiaoyitiao?token=` + res.data.thirdSession
             this.init()
             this.disableScroll()
           } 
         })
     
    },
    expand() {
      DemoApp.expand()
    },
    toggleMainButton() {
      DemoApp.toggleMainButton(this)
    },
   
  },
};
</script>

<style>
/* 根据需要添加样式 */

</style>
